<?php
namespace Common\Model;

class AdminModel extends CommonModel {
    /**
     * 登录验证
     * @param $username 账号
     * @param $password 密码(md5加密字符串)
     */
    function login($username, $password) {
        //查询
        $res = $this->field('aid,password,salt')->where(array('username' => $username))->find();
        //账号不存在
        if (empty($res)) {
            return false;
        }
        //密码错误
        $md5 = md5($password . $res['salt']);
        if ($md5 != $res['password']) {
            return false;
        }

        return $res;
    }

    /**
     * 注册
     * @param $username 账号
     * @param $password 密码
     */
    function reg($username, $password) {
        //检查重复
        if ($this->field('username')->where(array('username' => $username))->find()) {
            return false;
        }
        //添加
        $salt = \Org\Util\String::randString(6);
        $data = array(
            'username' => $username,
            'password' => md5(md5($password) . $salt),
            'salt' => $salt,
        );
        //返回
        $res = $this->add($data);
        if (!$res) {
            return false;
        }

        return true;
    }

    /**
     * 修改密码
     * @param $aid  用户ID
     * @param $old  旧密码
     * @param $new  新密码
     */
    function uppwd($aid, $old, $new) {
        //查询
        $res = $this->field('password,salt')->where(array('aid' => $aid))->find();
        if (!$res) {
            return false;
        }
        //验证
        if (md5(md5($old) . $res['salt']) != $res['password']) {
            return false;
        }
        //修改
        $salt = \Org\Util\String::randString(6);
        $data = array(
            'password' => md5(md5($new) . $salt),
            'salt' => $salt,
        );
        return $this->where(array('aid' => $aid))->save($data);
    }
}